/**
 * 
 */
package com.honghao.student.util;

import java.io.Serializable;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import com.honghao.student.pojo.Student;

/**
 * @author honghao.li
 * 
 */
public class RedisTest {

    private RedisTemplate<Serializable, Serializable> redisTemplate;

    public RedisTemplate<Serializable, Serializable> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(
            RedisTemplate<Serializable, Serializable> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void save(final Student student) {
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection)
                    throws DataAccessException {
                connection.set(
                        redisTemplate.getStringSerializer().serialize(
                                "stuid." + student.getStuId()),
                        redisTemplate.getStringSerializer().serialize(
                                student.getStuName()));
                return null;
            }
        });
    }

    public Student read(final int stuId) {
        return redisTemplate.execute(new RedisCallback<Student>() {

            @Override
            public Student doInRedis(RedisConnection connection)
                    throws DataAccessException {
                byte[] key = redisTemplate.getStringSerializer().serialize(
                        "stuid." + stuId);
                if (connection.exists(key)) {
                    byte[] value = connection.get(key);
                    String stuName = redisTemplate.getStringSerializer()
                            .deserialize(value);
                    Student stu = new Student();
                    stu.setStuName(stuName);;
                    return stu;
                }
                return null;
            }
        });
    }

    public void delete(final int stuId) {
        redisTemplate.execute(new RedisCallback<Object>() {

            public Object doInRedis(RedisConnection connection) {
                connection.del(redisTemplate.getStringSerializer().serialize(
                        "stuid." + stuId));
                return null;
            }
        });
    }
}
